function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatDate(date, split) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return [year, month, day].map(formatNumber).join(split || '')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function setDayVal(val) {
    var now = new Date();
    if (!/-?\d+/.test(val)) {
        return now;
    }
    now.setDate(now.getDate() + parseInt(val));
    return now;
}

Object.extend = function (a, b) { //合并对象
    if (typeof a !== "object" || typeof b !== "object") {
        return;
    }
    for (var key in b) {
        a[key] = b[key];
    }
    return a;
};

Object.extend(Date.prototype, {
  /***********格式化日期[YYYY|YY]-MM-DD hh:mm:ss*************/
  format: function (format) {
      var self = this;
      return format.replace(/([a-z]+)/ig, function (a, b, c, d) {
          if (/Y{2,}/.test(b)) {
              return b.length === 4 ? self.getFullYear() : ('' + self.getFullYear()).substr(2);
          } else if (/M{2}/.test(b)) {
              return (self.getMonth() + 1) < 10 ? '0' + (self.getMonth() + 1) : self.getMonth() + 1;
          } else if (/D{2}/.test(b)) {
              return (self.getDate()) < 10 ? '0' + self.getDate() : self.getDate();
          } else if (/h{2}/.test(b)) {
              return self.getHours() < 10 ? '0' + self.getHours() : self.getHours();
          } else if (/m{2}/.test(b)) {
              return self.getMinutes() < 10 ? '0' + self.getMinutes() : self.getMinutes();
          } else if (/s{2}/.test(b)) {
              return self.getSeconds() < 10 ? '0' + self.getSeconds() : self.getSeconds();
          } else {
              return 0;
          }
      })
  }
});

module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  setDayVal:setDayVal
}
